<template>
  <section class="project-detail" v-loading="loading">
    <div class="header-wrapper">
      <ProjectOverviewHeader
        :project="project"
        :completion-percentage="completionPercentage"
        :progress-color="progressColor"
        :completion-status="completionStatus"
        :requirement-total="projectRequirementCount"
        :requirement-completed="completedRequirementCount"
        :requirement-active="activeRequirementCount"
        :requirement-pending="pendingRequirementCount"
        @edit="handleEditProject"
        @delete="handleDeleteProject"
      />
    </div>

    <div class="main-content">
      <div class="content-wrapper">
        <div class="content-scroll">
          <ProjectDetailTabs
            v-model:active-tab="activeTab"
            :task-preview-list="taskPreviewList"
            :defect-preview-list="defectPreviewList"
            :requirement-preview-list="requirementPreviewList"
            :recent-activities="recentActivities"
            :tasks-loading="tasksLoading"
            :defects-loading="defectsLoading"
            :requirements-loading="requirementsLoading"
            :project-task-count="projectTaskCount"
            :completed-task-count="completedTaskCount"
            :active-task-count="activeTaskCount"
            :pending-task-count="pendingTaskCount"
            :project-defect-count="projectDefectCount"
            :open-defect-count="openDefectCount"
            :resolved-defect-count="resolvedDefectCount"
            :closed-defect-count="closedDefectCount"
            :project-requirement-count="projectRequirementCount"
            :completed-requirement-count="completedRequirementCount"
            :active-requirement-count="activeRequirementCount"
            :pending-requirement-count="pendingRequirementCount"
            @create-task="handleCreateTask"
            @view-tasks="handleViewTasks"
            @create-defect="handleCreateDefect"
            @view-defects="handleViewDefects"
            @create-requirement="handleCreateRequirement"
            @view-requirements="handleViewRequirements"
            @view-requirement="handleViewRequirement"
          />
        </div>
      </div>
      <div class="info-wrapper">
        <ProjectDetailSidebar
          :project="project"
          :project-members="projectMembers"
          @manage-members="handleManageMembers"
        />
      </div>
    </div>

    <ProjectDialog />
  </section>
</template>

<script setup lang="ts">
import { computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { deleteProject } from '@/api/project'
import ProjectOverviewHeader from './detail/components/ProjectOverviewHeader.vue'
import ProjectDetailSidebar from './detail/components/ProjectDetailSidebar.vue'
import ProjectDetailTabs from './detail/components/ProjectDetailTabs.vue'
import { useProjectDetail } from './detail/composables/useProjectDetail'
import ProjectDialog from '@/components/projects/ProjectDialog.vue'
import { useProjectDialogStore } from '@/stores/projectDialog'
import { usePermission } from '@/hooks/usePermission'
import { useStateStore } from '@/stores/state'
import { ModuleType } from '@/types/core'

const {
  loading,
  tasksLoading,
  defectsLoading,
  requirementsLoading,
  activeTab,
  projectId,
  project,
  projectMembers,
  recentActivities,
  taskPreviewList,
  defectPreviewList,
  requirementPreviewList,
  projectTaskCount,
  completedTaskCount,
  activeTaskCount,
  pendingTaskCount,
  projectDefectCount,
  openDefectCount,
  resolvedDefectCount,
  closedDefectCount,
  projectRequirementCount,
  completionPercentage,
  progressColor,
  completionStatus,
  completedRequirementCount,
  activeRequirementCount,
  pendingRequirementCount,
  loadProjectData,
  router
} = useProjectDetail()

const projectDialogStore = useProjectDialogStore()

// 权限检查
const { hasPermission } = usePermission()

// 权限计算属性
const canUpdateProject = computed(() => {
  return hasPermission('project:update') || 
         hasPermission('PROJECT_UPDATE') || 
         hasPermission('project:update_all') || 
         hasPermission('PROJECT_UPDATE_ALL')
})

const canDeleteProject = computed(() => {
  return hasPermission('project:delete') || 
         hasPermission('PROJECT_DELETE')
})

const handleEditProject = () => {
  if (!canUpdateProject.value) {
    ElMessage.warning('您没有编辑项目的权限')
    return
  }
  if (!projectId.value) {
    ElMessage.error('项目ID缺失，无法编辑')
    return
  }
  projectDialogStore.openEditDialog(projectId.value)
}

const handleDeleteProject = () => {
  if (!canDeleteProject.value) {
    ElMessage.warning('您没有删除项目的权限')
    return
  }
  ElMessageBox.confirm('确定要删除这个项目吗？此操作不可撤销。', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        await deleteProject(projectId.value)
        ElMessage.success('项目删除成功')
        router.push('/projects')
      } catch (error) {
        ElMessage.error('项目删除失败')
      }
    })
    .catch(() => {})
}

const handleCreateTask = () => {
  router.push(`/tasks/create?project_id=${projectId.value}`)
}

const handleViewTasks = () => {
  router.push(`/tasks?project_id=${projectId.value}`)
}

const handleCreateDefect = () => {
  router.push(`/defects/create?project_id=${projectId.value}`)
}

const handleViewDefects = () => {
  router.push(`/defects?project_id=${projectId.value}`)
}

const handleCreateRequirement = () => {
  router.push(`/requirements/create?project_id=${projectId.value}`)
}

const handleViewRequirements = () => {
  router.push(`/requirements?project_id=${projectId.value}`)
}

const handleViewRequirement = (id: string) => {
  router.push(`/requirements/${id}`)
}

const handleManageMembers = () => {
  router.push(`/projects/${projectId.value}/members`)
}

const stateStore = useStateStore()

onMounted(async () => {
  // 加载需求状态数据，确保状态映射正常工作
  await stateStore.fetchModuleStates(ModuleType.REQUIREMENT)
  loadProjectData()
})
</script>

<style scoped>
.project-detail {
  padding: 24px 40px 36px;
  min-height: calc(100vh - 80px);
  background: linear-gradient(180deg, #f0f4f8 0%, #ffffff 50%, #f8fafc 100%);
  display: flex;
  flex-direction: column;
  gap: 24px;
  box-sizing: border-box;
  position: relative;
}

.project-detail::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 200px;
  background: linear-gradient(135deg, rgba(64, 158, 255, 0.03) 0%, rgba(102, 177, 255, 0.02) 100%);
  pointer-events: none;
  z-index: 0;
}

.header-wrapper,
.main-content {
  position: relative;
  z-index: 1;
  width: 100%;
}

.header-wrapper {
  display: flex;
}

.header-wrapper :deep(.progress-area) {
  width: 100%;
}

.main-content {
  display: flex;
  gap: 24px;
}

.content-wrapper {
  flex: 1;
}

.info-wrapper {
  width: 320px;
  flex-shrink: 0;
  position: relative;
}

.info-wrapper :deep(.column-scroll) {
  max-height: calc(100vh - 260px);
}

.content-scroll {
  position: relative;
  flex: 1;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  box-shadow: 0 20px 60px rgba(15, 23, 42, 0.1), 0 8px 24px rgba(0, 0, 0, 0.06);
  overflow: hidden;
  padding: 24px;
  border: 1px solid rgba(255, 255, 255, 0.8);
  transition: all 0.3s ease;
}

.content-scroll:hover {
  box-shadow: 0 24px 72px rgba(15, 23, 42, 0.12), 0 12px 32px rgba(0, 0, 0, 0.08);
}

.content-scroll::after {
  content: '';
  position: absolute;
  inset: 0;
  pointer-events: none;
  border-radius: 20px;
  box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.6);
  z-index: 0;
}

.content-scroll > * {
  position: relative;
  z-index: 1;
}

:deep(.el-loading-mask) {
  border-radius: 20px;
  background-color: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(4px);
}

:deep(.el-loading-spinner) {
  margin-top: -25px;
}

:deep(.el-loading-spinner .circular) {
  width: 50px;
  height: 50px;
}

:deep(.el-card.content-card) {
  background: transparent;
  box-shadow: none;
  border: none;
  height: 100%;
}

:deep(.el-tabs--border-card) {
  border: none;
  box-shadow: none;
  background: transparent;
}

:deep(.el-tabs__header) {
  margin: 0;
  background: transparent;
}

:deep(.el-tabs__item) {
  font-weight: 500;
}

@media (max-width: 1400px) {
  .project-detail {
    padding: 20px 24px;
    gap: 20px;
  }

  .main-content {
    gap: 20px;
  }

  .info-wrapper {
    width: 280px;
  }

  .content-scroll {
    padding: 20px;
  }
}

@media (max-width: 1200px) {
  .project-detail {
    padding: 16px 20px;
    gap: 18px;
  }

  .main-content {
    flex-direction: column;
  }

  .info-wrapper {
    width: 100%;
  }

  .info-wrapper :deep(.column-scroll) {
    max-height: none;
  }

  .content-scroll {
    padding: 16px;
    border-radius: 16px;
  }
}

@media (max-width: 768px) {
  .project-detail {
    padding: 12px 16px;
    gap: 16px;
  }

  .content-scroll {
    padding: 16px 12px;
    border-radius: 12px;
  }
}
</style>